import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/themes/pageStyles.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/charts/quizTimes.dart';
import 'package:ichinesereader/widgets/charts/readBooks.dart';
import 'package:ichinesereader/widgets/charts/readTimes.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:ichinesereader/routes/routePages.dart';
import 'package:ichinesereader/widgets/sidebars/adminReportSidebar.dart';
import 'package:sidebarx/sidebarx.dart';

class SchoolAdminReportsOverall extends StatefulWidget {
  SchoolAdminReportsOverall({Key? key}) : super(key: key);
  static const String routeName = '/schooladmin/reports/overall';
  @override
  _SchoolAdminReportsOverallState createState() =>
      _SchoolAdminReportsOverallState();
}

class _SchoolAdminReportsOverallState extends State<SchoolAdminReportsOverall> {
  final ReportsController _reportsController = Get.find();
  final SchoolAdminController _schoolAdminController = Get.find();
  var box = Hive.box('appconfig');

  bool isSchoolAdmin = false;
  bool isYear = true;
  int? _selectedMonth;
  int? _initStartYear;
  int? _initEndYear;
  bool _toggle = false;
  DateTime today = DateTime.now();

  @override
  void initState() {
    isSchoolAdmin = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_SchoolAdmin;
    if (isSchoolAdmin) {
      if (_schoolAdminController.schoolAdminProfile.value.userId == null) {
        _schoolAdminController.fetchSchoolAdminProfile();
      }

      Future.delayed(Duration(milliseconds: 200), () {
        if (_schoolAdminController.schoolAdminProfile.value.accountStartDate !=
            null) {
          DateTime initStartDate = DateTime.fromMillisecondsSinceEpoch(
              _schoolAdminController
                  .schoolAdminProfile.value.accountStartDate!);

          String startTime = '${initStartDate.month}/${initStartDate.year}';
          String endTime = '${today.month}/${today.year}';

          setState(() {
            _initEndYear = today.year;
            _initStartYear = initStartDate.year;
          });
          if (_reportsController.schoolStaticsData.value.result == null)
            _reportsController.fetchSchoolStatisticList(
                startTime, endTime, isYear, true);
        }
      });
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build SchoolAdminReports');
    // final isSmallScreen =
    //     MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;
    final isBigScreen =
        MediaQuery.of(context).size.width > Constants.DefinedScreenBigSize;
    int _selectedSidebarItem = RoutePages.schoolAdminPageItems
        .indexWhere((page) => page.route == Get.currentRoute);
    final SidebarXController _xController = SidebarXController(
        selectedIndex: _selectedSidebarItem, extended: isBigScreen);
    final PageStyles _pageStyles = PageStyles();

    return Container(
      decoration: _pageStyles.pageBoxDecoration(),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: CustomAppBar(title: 'School Reports'.tr),
        body: Container(
          //decoration: _pageStyles.pageBoxDecoration(),
          child: Row(
            children: [
              Visibility(
                  //visible: !isSmallScreen,
                  visible: false,
                  child: AdminReportSidebarX(controller: _xController)),
              Expanded(
                child: SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  padding: const EdgeInsets.all(8.0),
                  child: Center(
                    child: Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Column(
                        children: [
                          DropdownButton(
                            icon: Icon(
                              Icons.arrow_drop_down_outlined,
                              color: Colors.blue[300],
                            ),
                            hint: Text('Daily Report'.tr),
                            value: _selectedMonth,
                            items:
                                ['------', ...Constants.allMonths].map((month) {
                              return DropdownMenuItem(
                                  value: Constants.allMonths
                                      .indexOf(month)
                                      .toInt(),
                                  child: Text(
                                    month,
                                    style:
                                        Theme.of(context).textTheme.titleSmall,
                                    overflow: TextOverflow.ellipsis,
                                  ));
                            }).toList(),
                            onChanged: (value) {
                              if (value as int > -1) {
                                Log.debug(value);

                                var month = value + 1;
                                var count = 0;
                                for (int year = _initStartYear!;
                                    year <= _initEndYear!;
                                    year++) {
                                  count++;
                                  String startTime = (month >= 10 ? '' : '0') +
                                      month.toString() +
                                      "/01/" +
                                      year.toString();

                                  var beginningNextMonth = (month < 12)
                                      ? new DateTime(year, month + 1, 1)
                                      : new DateTime(year + 1, 1, 1);
                                  var lastDay = beginningNextMonth
                                      .subtract(new Duration(days: 1))
                                      .day;

                                  String endTime = (month >= 10 ? '' : '0') +
                                      month.toString() +
                                      "/" +
                                      lastDay.toString() +
                                      "/" +
                                      year.toString();
                                  Future.delayed(
                                      Duration(milliseconds: count),
                                      () => _reportsController
                                          .fetchSchoolStatisticList(
                                              startTime,
                                              endTime,
                                              false,
                                              count ==
                                                  _initEndYear! -
                                                      _initStartYear! +
                                                      1));
                                }
                                setState(() {
                                  _selectedMonth = value;
                                  isYear = false;
                                  _toggle = !_toggle;
                                });
                              } else {
                                setState(() {
                                  _selectedMonth = value;
                                  isYear = true;
                                });
                              }
                            },
                          ),
                          _reportsController.obx(
                            (data) {
                              if (_reportsController
                                      .schoolStaticsData.value.result !=
                                  null) {
                                var datamap = isYear
                                    ? _reportsController
                                        .schoolStaticsData.value.result?.dataMap
                                    : _reportsController.schoolStaticsDataMonth
                                        .value.result?.dataMap;
                                if (datamap != null) {
                                  return Container(
                                    height: 400,
                                    width: context.width - 36,
                                    child: ReadBooksWidget(
                                        datamap: datamap,
                                        isYear: isYear,
                                        month: (_selectedMonth ?? 0) + 1),
                                  );
                                } else
                                  return Text('No data available'.tr);
                              } else {
                                return Text('');
                              }
                            },
                            onLoading: Container(),
                            // onLoading:
                            //     Center(child: CircularProgressIndicator()),
                          ),
                          Divider(),
                          _reportsController.obx(
                            (data) {
                              var datamap = isYear
                                  ? _reportsController
                                      .schoolStaticsData.value.result?.dataMap
                                  : _reportsController.schoolStaticsDataMonth
                                      .value.result?.dataMap;
                              if (datamap != null) {
                                return Container(
                                  height: 400,
                                  width: context.width - 36,
                                  child: ReadTimesWidget(
                                      datamap: datamap,
                                      isYear: isYear,
                                      month: (_selectedMonth ?? 0) + 1),
                                );
                              } else
                                return Text('No data available'.tr);
                            },
                            onLoading: Container(),
                            // onLoading:
                            //     Center(child: CircularProgressIndicator()),
                          ),
                          Divider(),
                          _reportsController.obx(
                            (data) {
                              var datamap = isYear
                                  ? _reportsController
                                      .schoolStaticsData.value.result?.dataMap
                                  : _reportsController.schoolStaticsDataMonth
                                      .value.result?.dataMap;
                              if (datamap != null) {
                                return Container(
                                  height: 400,
                                  width: context.width - 36,
                                  child: QuizTimesWidget(
                                      datamap: datamap,
                                      isYear: isYear,
                                      month: (_selectedMonth ?? 0) + 1),
                                );
                              } else
                                return Text('No data available'.tr);
                            },
                            onLoading: Container(),
                            // onLoading:
                            //     Center(child: CircularProgressIndicator()),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
